from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from contextlib import asynccontextmanager
import asyncio
import ormOB

class DatabaseManager:
    def __init__(self, db_url):
        self.engine = create_async_engine(
            db_url,
            pool_size=20,
            max_overflow=10,
            pool_timeout=30
        )

    @asynccontextmanager
    async def get_session(self):
        """获取异步会话"""
        async with AsyncSession(self.engine) as session:
            try:
                yield session
                await session.commit()
            except Exception:
                await session.rollback()
                raise

# db_config = {
#     "dialect": "mysql",
#     "host": "localhost",
#     "user": "root",
#     "password": "111111",
#     "database": "gardevoir",
#     "port": 3306
# }
#
# db_url = f"mysql+aiomysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['database']}"
#
# new_danmu = ormOB.Danmaku(id=1,danmu_user='test01',content='test02')
#
# databaseManager = DatabaseManager(db_url=db_url)
#
# # 异步函数，用于提交数据
# async def add_danmu():
#     async with databaseManager.get_session() as session:
#         session.add(new_danmu)
#
# # 主函数
# async def main():
#     await add_danmu()
#     # 显式关闭引擎
#     await databaseManager.engine.dispose()
#
# # 运行主函数
# asyncio.run(main())
